const User = require("../model/UserModel");

class UserDao {
  async save(data) {
    const res = await User.create(data);
    res.dataValues.HidePhoneNumber = res.getHidePhoneNumber();
    res.dataValues.HideCardNo = res.getHideCardNo();
    res.Password = "";
    return res.toJSON();
  }

  async update(data) {
    let { Id, AvatarUrl, Nickname, Sex, Birthday, Description, Email } = data;
    const res = await User.update(
      {
        Id,
        AvatarUrl,
        Nickname,
        Sex,
        Birthday,
        Description,
        Email,
      },
      {
        where: {
          Id,
        },
      }
    );
    const r = await this.getOneById(Id);
    return r;
  }

  async delete(Id) {
    const res = await User.destroy({
      where: {
        Id,
      },
    });
    return true;
  }

  async getOneById(Id) {
    const res = await User.findByPk(Id);
    if (res?.dataValues) {
      res.dataValues.HidePhoneNumber = res.getHidePhoneNumber();
      res.dataValues.HideCardNo = res.getHideCardNo();
      res.dataValues.Password = "";
      return res.toJSON();
    }

    return null;
  }

  async getOneByPhoneNumber(PhoneNumber) {
    const res = await User.findOne({
      where: {
        PhoneNumber,
      },
    });
    if (res?.dataValues) {
      res.dataValues.HidePhoneNumber = res.getHidePhoneNumber();
      res.dataValues.HideCardNo = res.getHideCardNo();
      res.Password = "";
      return res.toJSON();
    }
    return null;
  }

  async getUserBaseInfo(UserId) {
    const result = await this.getOneById(UserId);
    if (result) {
      delete result.Password;
      delete result.TrueName;
      delete result.CardNo;
      delete result.PhoneNumber;
      delete result.HideCardNo;
      delete result.HidePhoneNumber;
    }
    return result;
  }
}
module.exports = new UserDao();
